const { createCanvas, loadImage } = require('canvas');

const ratio = 0.3; //进行比例


function watermark(pic, wm) {
    loadImage(pic).then(myImg => {
        loadImage(wm).then(wmimg => {
            const canvas = createCanvas(myImg.width, myImg.height)
            const ctx = canvas.getContext('2d');
            ctx.drawImage(myImg, 0, 0)

            //计算旋转贴图的最大需要尺寸 矩形的对角线
            const long = Math.sqrt(wmimg.width * wmimg.width + wmimg.height * wmimg.height)
            const halfong = long / 2;
            //获取背景图的最长边长
            const bglong = Math.max(myImg.width, myImg.height)
                //计算贴图的缩放比
            const signscale = bglong / long * ratio;

            //贴图的画布边长按比例缩放
            const wmlong = long * signscale

            //创建贴图的画布
            const canvas1 = createCanvas(wmlong, wmlong)
                //获取贴图的绘图区
            const ctx1 = canvas1.getContext('2d')
                //贴图绘图区缩放
            ctx1.scale(signscale, signscale)
                //绘图区移到中心点
            ctx1.translate(halfong, halfong)
                //贴图的绘图区围绕中心点旋转随机角度
            ctx.rotate((Math.random() - 0.5) * Math.PI / 2)
                //绘图区移到原点
            ctx1.translate(-halfong, -halfong)
                //绘制贴图到贴图绘图区
            ctx1.drawImage(wmimg, (long - wmimg.width) / 2, (long - wmimg.height) / 2)
                //随机生成背景图上的粘贴位置
            const posx = (myImg.width - wmlong) * Math.random();
            const posy = (myImg.height - wmlong) * Math.random();
            //贴图绘制到背景图上
            ctx.drawImage(canvas1, posx, posy)


            const fs = require('fs')
            const out = fs.createWriteStream(__dirname + '/' + pic)
            const stream = canvas.createPNGStream()
            stream.pipe(out)
            out.on('finish', () => console.log("png file created。"));
        })
    })
}
module.exports = watermark
    //watermark('./uploads/400.jpg', './uploads/sky.png') //测试数据